﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace CarShopManagerDAL
{
    public class DBHelper
    {
        //定义链接字符串
        private static string constr = ConfigurationManager.ConnectionStrings["ConStr"].ToString();
        //创建链接对象
        private static SqlConnection conn = new SqlConnection(constr);
        /// <summary> 
        /// 查询
        /// </summary>
        /// <param name="sql">要执行的sql语句</param>
        /// <returns>返回DataTable类型的结果集</returns>
        public static DataTable GetTable(string sql)
        {
            //执行sql语句
            SqlCommand cmd = new SqlCommand(sql, conn);
            //创建适配器对象
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            //创建datatable对象
            DataTable dt = new DataTable();
            //将适配后的结果填充到dt中
            sda.Fill(dt);
            return dt;
        }
        /// <summary>
        /// 增删改
        /// </summary>
        /// <param name="sql">要执行的sql语句</param>
        /// <returns>返回受影响的行数</returns>
        public static int ExcuteNonQuery(string sql)
        {
            //打开链接
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
            //执行sql语句
            SqlCommand cmd = new SqlCommand(sql, conn);
            //获取受影响的行数
            int r = cmd.ExecuteNonQuery();
            //关闭链接
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
            }
            return r;
        }
    }
}
